package cn.echogo.framework.image;

import java.io.FileNotFoundException;
import java.lang.ref.SoftReference;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;

public class CompTouchView extends LinearLayout implements OnTouchListener {

	private ImageView photoBrowse;
	private Bitmap bm;
	private int displayWidth = 0;
	private int displayHeight = 0;
	// 手势操作变量！
	private static final String TAG = "Touch";
	Matrix matrix = new Matrix();
	Matrix savedMatrix = new Matrix();

	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;
	// We can be in one of these 3 states
	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	int mode = NONE;
	int imageWidth;
	int imageHeight;
	private SoftReference<Bitmap> sr;
	private Context context;
	static float x1, y1;

	public CompTouchView(Context context) {
		super(context);
		this.context = context;
	}

	public CompTouchView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		setBackgroundColor(Color.WHITE);
	}

	public void initTouchView(Bitmap bm) {
		sr = new SoftReference<Bitmap>(bm);
		// this.bm = bm;
		photoBrowse = new ImageView(context);
		photoBrowse.setScaleType(ScaleType.CENTER_CROP);
		/* 取得屏幕宽高 */
		// 取得屏幕分辨北率
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		displayWidth = dm.widthPixels;
		displayHeight = dm.heightPixels;
		// 计算当前图片的宽和高
		photoBrowse.setImageBitmap(sr.get());
		imageWidth = sr.get().getWidth();
		imageHeight = sr.get().getHeight();
		photoBrowse.setOnTouchListener(this);

		x1 = (displayWidth - imageWidth) / 2;
		y1 = (displayHeight - imageHeight) / 2;
		removeAllViews();
		// addView(photoBrowse, new
		// LayoutParams(ViewUtil.getDisplayMetrics(context).widthPixels,
		// ViewUtil.getDisplayMetrics(context).heightPixels));
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		ImageView view = (ImageView) v;
		view.setScaleType(ScaleType.MATRIX);
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			savedMatrix.set(matrix);
			// 設置初始點位置
			start.set(event.getX(), event.getY());
			mode = DRAG;
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			oldDist = spacing(event);
			if (oldDist > 10f) {
				savedMatrix.set(matrix);
				midPoint(mid, event);
				mode = ZOOM;
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			mode = NONE;
			Log.d(TAG, "mode=NONE");
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == DRAG) {
				// ...
				matrix.set(savedMatrix);
				matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
			} else if (mode == ZOOM) {
				float newDist = spacing(event);
				Log.d(TAG, "newDist=" + newDist);
				if (newDist > 10f) {
					matrix.set(savedMatrix);
					float scale = newDist / oldDist;
					matrix.postScale(scale, scale, mid.x, mid.y);
				}
			}
			break;
		}
		view.setImageMatrix(matrix);
		return true; // indicate event was handled
	}

	/** Determine the space between the first two fingers */
	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	/** Calculate the mid point of the first two fingers */
	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}

	/**
	 * 当切换的时候回收资源
	 */
	protected void onDestroy(Bitmap bm) {
		bm.recycle();
		bm = null;
	}

	/**
	 * 当切换的时候回收资源
	 */
	protected void onDestroy() {
		bm.recycle();
		bm = null;
	}

	public void setImageResource(Integer resId) {
		// Bitmap bit =bm;
		Resources res = context.getResources();
		Bitmap bitmap = BitmapFactory.decodeResource(res, resId);
		initTouchView(bitmap);
		matrix = new Matrix();
		photoBrowse.setImageResource(resId);
		// if( bit != null&&!bit.isRecycled())
		// onDestroy(bit);
	}

	public void setImageBitmap(Bitmap bitmap) {
		// Bitmap bit =bm;
		initTouchView(bitmap);
		matrix = new Matrix();
		photoBrowse.setImageBitmap(bitmap);
		// if( bit != null&&!bit.isRecycled())
		// onDestroy(bit);
	}

	public void setImageDrawable(Drawable drawable) {
		// Bitmap bit =bm;
		initTouchView(drawableToBitmap(drawable));
		matrix = new Matrix();
		photoBrowse.setImageDrawable(drawable);
		// if( bit != null&&!bit.isRecycled())
		// onDestroy(bit);
	}

	/**
	 * 将Drawable转化为Bitmap
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();
		Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);
		drawable.draw(canvas);
		return bitmap;

	}

}